<template>
  <div class="permission-application-container">
    <el-card>
      <h2>权限申请</h2>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        @submit.prevent="handleSubmit"
      >
        <!-- 用户ID（隐藏，从登录态获取） -->
        <el-form-item label="用户ID" prop="user_id">
          <el-input v-model="form.user_id" disabled />
        </el-form-item>

        <!-- 申请权限类型 -->
        <el-form-item label="申请权限" prop="applied_role">
          <el-select v-model="form.applied_role" placeholder="请选择申请的权限">
            <el-option label="客服" value="1" />
            <el-option label="站点" value="2" />
            <el-option label="维修员" value="3" />
          </el-select>
        </el-form-item>

        <!-- 申请备注 -->
        <el-form-item label="申请备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请填写申请原因（可选）"
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" :loading="isLoading" :disabled="isLoading" native-type="submit">
            {{ isLoading ? '提交中...' : '提交申请' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { submitRoleApplication } from '@/api/user'
import { ElMessage } from 'element-plus'

// 表单数据初始化（从登录态获取用户ID）
const form = ref({
  user_id: '', // 从localStorage获取当前用户ID
  applied_role: null, // 申请的权限类型（1-3）
  remark: '', // 备注（可选）
})

// 加载状态和提示信息
const isLoading = ref(false)
const message = ref('')

// 表单校验规则
const rules = ref({
  user_id: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  applied_role: [{ required: true, message: '请选择申请的权限类型', trigger: 'change' }],
})

// 表单引用
const formRef = ref(null)

// 初始化用户ID（从localStorage获取）
const initUserInfo = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo'))
  if (userInfo) {
    form.value.user_id = userInfo._id // 假设用户ID字段为_id
  }
}

// 提交申请
const handleSubmit = async () => {
  isLoading.value = true
  message.value = ''

  // 表单校验
  const valid = await new Promise((resolve) => {
    formRef.value.validate((valid) => resolve(valid))
  })

  if (!valid) {
    isLoading.value = false
    return
  }

  // 调用权限申请接口
  try {
    form.value.applied_role = parseInt(form.value.applied_role)
    form.value.application_type = 'role_upgrade'
    const res = await submitRoleApplication(form.value)
    if (res.code === 201) {
      ElMessage({
        message: '权限申请提交成功',
        type: 'success',
      })
      // 重置表单
      form.value = { user_id: form.value.user_id, applied_role: '', remark: '' }
    } else {
      ElMessage({
        message: res.message || '权限申请提交失败',
        type: 'error',
      })
    }
  } catch (err) {
    ElMessage({
      message: '权限申请提交失败' + err,
      type: 'error',
    })
    console.log(err)
  } finally {
    isLoading.value = false
  }
}

// 组件挂载时初始化用户ID
initUserInfo()
</script>

<style scoped>
.permission-application-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.message {
  margin-top: 15px;
}
</style>
